﻿#region Usings

using System;
using System.Data.Entity;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;
using Newtonsoft.Json;
using Ninject;
using xConnected.Core.Interfaces.Service;
using xConnected.Data;
using xConnected.Helpers;

#endregion

namespace xConnected
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : HttpApplication
    {
        public override void Init()
        {
            AuthenticateRequest += MvcApplication_AuthenticateRequest;
            AcquireRequestState += MvcApplication_AcquireRequestState;
        }

        private void MvcApplication_AcquireRequestState(object sender, EventArgs e)
        {
            //HttpSessionState session = HttpContext.Current.Session;
            //if (session == null) return;

            //if (session["User"] == null)
            //{
            //    if (HttpContext.Current.User != null)
            //    {
            //        var kernel = new StandardKernel();
            //        try
            //        {
            //            var userService = DependencyResolver.Current.GetService<IUserService>(); //kernel.Get<IUserService>();

            //            var user = userService.GetUserByUsername(HttpContext.Current.User.Identity.Name);
            //            if (user != null)
            //                session["User"] = user;
            //        }
            //        catch
            //        {
            //            // surpress this exception...
            //        }
            //    }
            //}
        }

        private void MvcApplication_AuthenticateRequest(object sender, EventArgs e)
        {
           var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
           if (authCookie != null)
           {
               var encTicket = authCookie.Value;
               if (!String.IsNullOrEmpty(encTicket))
               {
                   var ticket = FormsAuthentication.Decrypt(encTicket);
                   var identity = new GenericIdentity(ticket.Name);
                   //var roles = ticket.UserData.Split(',');
                   var principal = new GenericPrincipal(identity, new string[]{});
                   HttpContext.Current.User = principal;
               }
           }
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            //Database.SetInitializer(new CustomContextInitializer());

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().FirstOrDefault());
            ValueProviderFactories.Factories.Add(new JsonNetValueProviderFactory());

            log4net.Config.XmlConfigurator.Configure();

            // WebApi Configuration to hook up formatters and message handlers
            // optional
            RegisterApis(GlobalConfiguration.Configuration);
        }

        public static void RegisterApis(HttpConfiguration config)
        {
            // Add JavaScriptSerializer  formatter instead - add at top to make default
            //config.Formatters.Insert(0, new JavaScriptSerializerFormatter());

            // Add Json.net formatter - add at the top so it fires first!
            // This leaves the old one in place so JsonValue/JsonObject/JsonArray still are handled
            //config.Formatters.Insert(0, new JsonNetFormatter());

            config.Formatters.Remove(config.Formatters.XmlFormatter);
            var js = config.Formatters.JsonFormatter;
            js.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
        }

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

            routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            routes.MapHttpRoute(
                name: "ActionApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }
        
    }
}